import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzBackTopModule } from 'ng-zorro-antd/back-top';

@Component({
  selector: 'app-list4',
  standalone: true,
  templateUrl: './list4.component.html',
  imports: [
    NzButtonModule,
    NzBackTopModule,
  ],
  styleUrls: ['./list4.component.css']
})
export class List4Component implements OnInit {
  @ViewChild('scrollContainer', { static: false }) scrollContainer!: ElementRef;

  constructor(private message: NzMessageService) {}

  items: number[] = [];
  loading = false;
  isLoadingInit = false;
  hasMore = true;
  containerHeight = 400; // 容器高度
  scrollThreshold = 20;  // 滚动阈值

  ngOnInit(): void {
    this.loadMoreItems(10); // 初始加载
  }
  
  // 初始化数据
  initItem(){
    // 初始化数据
    this.items = [];
    this.isLoadingInit = true;
    this.hasMore = true;
    // 模拟加载更多数据
    setTimeout(() => {
      this.loadMoreItems(10); // 初始加载
      this.isLoadingInit = false;
    }, 2000);
  }

  onScroll(event: Event): void {
    const target = event.target as HTMLElement;
    const scrollTop = target.scrollTop;
    const scrollHeight = target.scrollHeight;
    const clientHeight = target.clientHeight;

    // console.log('scrollTop', scrollTop);
    // console.log('scrollHeight', scrollHeight);
    // console.log('clientHeight', clientHeight);
    // console.log('this.hasMore', this.hasMore);
    // console.log('this.loading', this.loading);
    // console.log('scrollTop + clientHeight', scrollTop + clientHeight)
    // console.log('scrollHeight - this.scrollThreshold', scrollHeight - this.scrollThreshold)
    if (scrollTop + clientHeight >= scrollHeight - this.scrollThreshold && this.hasMore && !this.loading) {
      this.loadMore();
    }
  }

  loadMore(): void {
    if (this.loading || !this.hasMore) return;

    this.loading = true;
    // 模拟API调用
    setTimeout(() => {
      this.loadMoreItems(10);
      this.loading = false;

      // 如果没有更多数据，则设置hasMore为false
      if (this.items.length >= 50) {
        this.message.info('没有更多数据了...');
        this.hasMore = false;
      }
    }, 1000);
  }

  loadMoreItems(count: number): void {
    // let list = []
    // let length = this.items.length
    // for(let i=0; i<count; i++) {
    //   list.push(length + i + 1); // 模拟添加数据，需要根据实际情况修改为从API获取数据并添加到items中
    // }
    // this.items = [...this.items, ...list];

    const newItems = Array.from({ length: count }, (_, i) => this.items.length + 1 + i);
    this.items = [...this.items, ...newItems];
  }
}
